package com.oig.sys.base.controller;

import cn.hutool.core.util.StrUtil;
import com.oig.common.exception.BadRequestException;
import com.oig.common.module.SysRequest;
import com.oig.common.module.SysResponse;
import com.oig.common.util.JsonUtil;
import com.oig.common.validator.GroupAdd;
import com.oig.common.validator.GroupEdit;
import com.oig.sys.base.dto.AreaDto;
import com.oig.sys.base.dto.AreaJsonDto;
import com.oig.sys.base.service.ITbAreaService;
import com.oig.sys.base.vo.AreaVo;
import com.oig.sys.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Tag(name = "行政区划")
@RestController
@RequestMapping("/area")
@Slf4j
public class TbAreaController {

    private final ITbAreaService areaService;

    @Autowired
    public TbAreaController(ITbAreaService areaService){
        this.areaService = areaService;
    }


    @PreAuthorize("@pms.hasPermission('/area/add')")
    @SysLog(value="添加行政地区",apiUrl="/area/add")
    @Operation(summary = "添加行政地区")
    @PostMapping(value = "/add")
    public AreaVo add(@RequestBody @Validated(GroupAdd.class) AreaDto areaDto){
        log.info("add area {}",areaDto);
        return this.areaService.addArea(areaDto);
    }

    @PreAuthorize("@pms.hasPermission('/area/update')")
    @SysLog(value="修改行政地区",apiUrl="/area/update")
    @Operation(summary = "修改行政地区")
    @PostMapping(value = "/update")
    public AreaVo update(@RequestBody @Validated(GroupEdit.class) AreaDto areaDto){
        log.info("update area{}",areaDto);
        return this.areaService.updateArea(areaDto);
    }

    @PreAuthorize("@pms.hasPermission('/area/cancel')")
    @SysLog(value="逻辑删除行政地区",apiUrl="/area/cancel")
    @Operation(summary = "逻辑删除行政地区")
    @PostMapping(value = "/cancel/{id}")
    public SysResponse<Integer> cancel(@PathVariable("id") Integer id){
        log.info("cancel Country Group id={}", id) ;
        this.areaService.cancelArea(id);
        return SysResponse.ok(id,"逻辑删除成功");
    }


    @Operation(summary = "查询行政区划,根据名称查询")
    @PostMapping(value = "/findAreaByName/{name}")
    public AreaVo findAreaByName(@PathVariable("name")String name){
        log.info("find Area by name= {}", name);
        return this.areaService.findAreaByName(name);
    }

    @Operation(summary = "查询行政区划,根据上级id查询")
    @PostMapping(value = "/listArea/{parentId}")
    public List<AreaVo> listArea(@PathVariable("parentId") Integer parentId){
        log.info("list Area, {}", parentId);
        return this.areaService.listArea(parentId);
    }

    @Operation(summary = "查询备选地址,多条件")
    @PostMapping(value = "/findArea")
    public List<AreaVo> findArea(@RequestBody SysRequest<AreaDto> areaRequest){
        log.info("find area:{}", areaRequest);
        return this.areaService.queryArea(areaRequest);
    }

    @Operation(summary = "查询返回树形列表")
    @PostMapping(value = "/findAreaTree")
    public List<AreaVo> findAreaTree(@RequestParam(name = "countryCode", required = false)String countryCode){
        if (StrUtil.isBlank(countryCode)){
            countryCode = "156";
        }
        log.info("find area:{}", countryCode);
        return this.areaService.findAreaTree(countryCode);
    }


    /**
     * 加些批量导入等操作
     */
    @PreAuthorize("@pms.hasPermission('/area/importAreas')")
    @SysLog(value="批量导入行政地区",apiUrl="/area/importAreas")
    @PostMapping("/importAreas/{countryCode}")
    @Operation(summary = "批量导入,json 文件导入")
    public List<AreaVo> importAreas(@PathVariable("countryCode") String countryCode, @RequestPart("jsonFile") MultipartFile jsonFile){
        log.info("import areas country:{}",countryCode);
        if (jsonFile == null || jsonFile.getSize() == 0 || StrUtil.isBlank(jsonFile.getOriginalFilename())) {
            throw new BadRequestException("空文件");
        }
        InputStream in = null;
        try{
            in = jsonFile.getInputStream();
            String json = IOUtils.toString(in, StandardCharsets.UTF_8);
            log.info(json);
            List<AreaJsonDto> areaJsonDtoList = JsonUtil.toList(json, AreaJsonDto.class);
            return this.areaService.addAllArea(countryCode, areaJsonDtoList);
        } catch (IOException e){
            log.error("file upload error", e);
        } finally {
            IOUtils.closeQuietly(in);
        }
        return null;
    }

}
